package com.hellacutty.shake;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/*
 * This class waits for messages from the BT opponent and updates its shake count accordingly for drawing.
 */
public class BluetoothOpponentShakeListener implements CanProvideShakes{
	private BluetoothChatService _btService;
	private Handler _handler;
	private int shakeCount;
	private Context _context;
	private CanvasActivity2Player _drawer;
	@Override
	public int getShakeCount() {
		return shakeCount;
	}

	public BluetoothOpponentShakeListener(BluetoothChatService service, Context context, CanvasActivity2Player drawer){
		_drawer = drawer;
		_context = context;
		_btService = service;
		//set the handler of the service to reflect what
		_handler = new Handler(){
			@Override
			public void handleMessage(Message msg){
				switch(msg.what){
				case BluetoothChat.MESSAGE_READ:
					Log.d("SHAKE", "Reading message from handler in BluetoothOpponentSHakeListner");
					byte[] readBuf = (byte[])msg.obj;
					String readMessage = new String(readBuf, 0, msg.arg1);
					String[] toked = readMessage.split(",");
					if(toked[0].equals(ProtocolConstants.SHAKE_PING)){
//						Log.d("SHAKE", "shake counts incremented in BTOpponentShakeListener: " + toked[1]);
//						Log.d("SHAKE", "length of toked message: " + toked.length);
//						Log.d("SHAKE", readMessage);
							try {
								int newShakes = Integer.parseInt(toked[1]);
								//If this message gives an old shake count (outated message), ignore it
								if(newShakes > shakeCount){
									shakeCount = newShakes;
								}else{
									Log.d("SHAKE", "outdated shake count");
								}
							} catch (NumberFormatException e) {
								//if not number, check if other parts of message are win message
								for(String s : toked){
									if(s.equals(ProtocolConstants.OPPONENT_WIN)){
										Log.d("SHAKE", "win came from corrupt message.");
										handleWin();
									}
								}
							}
					}
					else if(toked[0].equals(ProtocolConstants.OPPONENT_WIN)){
						_drawer.setShouldDraw(false);
						Toast.makeText(_context, "YOU LOST!", Toast.LENGTH_LONG).show();
					}
					break;
				}
			}
		};
		_btService.setHandler(_handler);

	}

	public void handleWin(){
		_drawer.setShouldDraw(false);
		Toast.makeText(_context, "YOU LOST!", Toast.LENGTH_LONG).show();
	}
}
